﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace AllInServiceAuthorization
{
    /// <summary>
    /// 提供 Token 服务的实现。
    /// </summary>
    public sealed class JWTService : IJWTService
    {
        private readonly IOptionsMonitor<JWTTokenOption> _option;

        /// <summary>
        /// 实例化。
        /// </summary>
        /// <param name="option">注入选项。</param>
        public JWTService(IOptionsMonitor<JWTTokenOption> option)
        {
            _option = option;
        }

        /// <summary>
        ///  获取 Token。
        /// </summary>
        /// <param name="userName">用户名。</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public string GetToken(string userName, string password)
        {
            #region 有效载荷

            var claims = new[] {
             new Claim(ClaimTypes.Name, userName),
             new Claim("NickName",userName),
             new Claim(ClaimTypes.Role,"Administrator"),
             new Claim("Password",password),
             };

            #endregion

            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_option.CurrentValue.SecurityKey!));

            SigningCredentials signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: _option.CurrentValue.Issuer!,
                audience: _option.CurrentValue.Audience!,
                claims: claims,
                expires: DateTime.Now.AddMinutes(5),
                signingCredentials: signingCredentials
);

            string returnToken = new JwtSecurityTokenHandler().WriteToken(token);

            return returnToken;
        }
    }

}
